package biz.yfsoft.app.fastframework.admin;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import biz.yfsoft.app.fastframework.core.Fast;
import biz.yfsoft.app.fastframework.core.hex.EmailNotExistsException;
import biz.yfsoft.app.fastframework.core.hex.TokenInvalidException;
import biz.yfsoft.app.fastframework.interceptor.BehaviorInterceptor;
import biz.yfsoft.app.fastframework.plugin.mail.Mailer;
import biz.yfsoft.app.fastframework.plugin.sms.Sms;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.kit.StrKit;


public class NotifyController extends AdminController {
	
	public void index() {
		if(hasConfig("EMAIL_CONFIG")){
			String config = getConfig("EMAIL_CONFIG",null);
			if(!StrKit.isBlank(config)){
				JSONObject c = JSONObject.parseObject(config);
				this.setAttr("emailConfig", c);
			}
		}
		render("/admin/notify.jsp");
	}
	
	@ClearInterceptor(ClearLayer.ALL)
	public void emailNotify(){
		//发送带图片的邮件
		HtmlEmail htmlEmail = Mailer.getHtmlEmail("Hello", "fan.wang@rd.imap360.com");
		try {
			htmlEmail.setHtmlMsg("<a href='www.dreampie.cn'>Dreampie</a><img src=\"http://search.maven.org/ajaxsolr/images/centralRepository_logo.png\"'/>");
			htmlEmail.send();
		} catch (EmailException e) {
			e.printStackTrace();
		}
		
		renderText("1");
	}
	
	public void confEmail(){
		Map<String,Object> args = this.getParams();
		JSONObject jo = new JSONObject(args);
		this.setConfig("EMAIL_CONFIG", jo.toJSONString());
		//TODO:重新加载邮箱配置
		renderJson(wrapJson(0));
	}
	
	/**
	 * 来自支付平台的消息回调
	 * 支付完成之后会收到icbc发送过来的消息，处理消息的有效性和安全性，然后通过webhook的方式进行一次方法的调用
	 */
	@ClearInterceptor(ClearLayer.ALL)
	@Before(BehaviorInterceptor.class)
	public void payNotify(){
		System.out.println("NOTIFY:"+this.getParams().toString());
		renderText("1");
	}
	
	@ClearInterceptor(ClearLayer.ALL)
	public void sendSms(){
		Map<String,String> args = new HashMap<String,String >();
//		args.put("code","111");
		renderText(String.valueOf(Sms.send("13770683580", "4084",args )));
		
	}
	
	@ClearInterceptor(ClearLayer.ALL)
	public void forgetPass(){
		String email = getPara("email");
		try {
			Fast.me().findPassByEmail(email);
		} catch (EmailNotExistsException e) {
			renderText(e.getMessage());
			return;
		}
		renderText("OK");
	}
	
	@ClearInterceptor(ClearLayer.ALL)
	public void resetPass(){
		String token = getPara(0);
		String newPass = getPara("newPass","123123"); 
		try {
			Fast.me().resetPass(token, newPass);
		} catch (TokenInvalidException e) {
			renderText(e.getMessage());
			return;
		}
		renderText("OK");
	}
}
